package com.gxks.lhs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxks.lhs.entity.Goods;
import com.gxks.lhs.mapper.GoodsMapper;
import com.gxks.lhs.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author LuoHaisong
 * @since 2023-05-18
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public boolean removeGoods(List<String> idList) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Goods::getId, idList);
        return remove(queryWrapper);
    }

    @Override
    public boolean removeGoodsById(String id) {
        return removeById(id);
    }

    @Override
    public boolean updateGoodsStatus(String id, Integer status) {
        return update(new Goods().setStatus(status), new QueryWrapper<Goods>().lambda().eq(Goods::getId, id));
    }


    @Override
    public boolean updateGoods(Goods goods) {
        return updateById(goods);
    }

    /**
     * 更新用户商品信息。
     *
     * @param goods 包含商品更新信息的对象。商品ID用于查找现有商品，其余字段用于更新。
     * @return 如果商品成功更新，则返回true；如果商品不存在、商品状态为2、或者商品用户ID不匹配，则返回false。
     */
    @Override
    public boolean updateGoodsforUser(Goods goods) {
        // 根据商品ID获取当前商品
        Goods goods1 = getById(goods.getId());
        // 如果商品不存在，则返回false
        if (goods1 == null) {
            return false;
        }
        // 如果商品状态为2（表示已卖出），则不进行更新操作
        if (goods1.getStatus() == 2) {
            return false;
        }
        // 确保商品的当前用户ID与更新请求中的用户ID一致，否则不允许更新
        if (!goods1.getUserId().equals(goods.getUserId())) {
            return false;
        }
        // 构建更新包装器，动态设置需要更新的字段
        LambdaUpdateWrapper<Goods> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(goods.getTitle() != null, Goods::getTitle, goods.getTitle())
                .set(goods.getCategoryId() != null, Goods::getCategoryId, goods.getCategoryId())
                .set(goods.getPrice() != null, Goods::getPrice, goods.getPrice())
                .set(goods.getStorage() != null, Goods::getStorage, goods.getStorage())
                .set(goods.getDegree() != null, Goods::getDegree, goods.getDegree())
                .set(goods.getDescription() != null, Goods::getDescription, goods.getDescription())
                .set(goods.getPictureList() != null, Goods::getPictureList, goods.getPictureList())
                .set(goods.getPicture() != null, Goods::getPicture, goods.getPicture())
                .eq(Goods::getId, goods.getId());
        // 执行更新操作并返回结果
        return update(lambdaUpdateWrapper);
    }


    @Override
    public Page<Goods> findAllGoods(Integer current, Integer size) {
        return page(new Page<>(current, size));
    }

    @Override
    public Page<Goods> findGoods(Goods goods, Integer current, Integer size) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(goods.getTitle() != null, Goods::getTitle, goods.getTitle())
                .like(goods.getUserName() != null, Goods::getUserName, goods.getUserName())
                .eq(goods.getCategoryId() != null, Goods::getCategoryId, goods.getCategoryId())
                .eq(goods.getStatus() != null, Goods::getStatus, goods.getStatus());
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Goods findGoodsById(String id) {
        return getById(id);
    }

    @Override
    public boolean addGoods(Goods goods) {
        return save(goods);
    }

    @Override
    public Page<Goods> findGoodsByUserId(String userId, Integer current, Integer size) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Goods::getUserId, userId)
                .ne(Goods::getStatus, 2)
                .orderByDesc(Goods::getCreateTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public boolean soldOut(String userId, String GoodsId) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<Goods>();
        updateWrapper.eq(Goods::getUserId, userId).eq(Goods::getId, GoodsId).set(Goods::getStatus, 0);
        return update(updateWrapper);
    }

    @Override
    public boolean soldIn(String userId, String GoodsId) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<Goods>();
        updateWrapper.eq(Goods::getUserId, userId).eq(Goods::getId, GoodsId).set(Goods::getStatus, 1);
        return update(updateWrapper);
    }

    @Override
    public boolean removeGoods(String userId, String GoodsId) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<Goods>();
        updateWrapper.eq(Goods::getUserId, userId).eq(Goods::getId, GoodsId).eq(Goods::getStatus, 0).set(Goods::getIsDeleted, 1);
        return update(updateWrapper);

    }

    @Override
    public List<Goods> randomFindGoodsList() {

        return goodsMapper.randomFindGoodsList();
//       随机查询10条二手手机信息
//        @Select("SELECT * FROM user WHERE deleted = 0 ORDER BY RAND() LIMIT 10")

//        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().orderByDesc(Goods::getCreateTime);
//        queryWrapper.last("limit 10");
//        return page(new Page<>(1, 10), queryWrapper);
    }

    @Override
    public Page<Goods> findGoodsList(Integer categoryId, Integer current, Integer size) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(categoryId != 0, Goods::getCategoryId, categoryId);
        queryWrapper.lambda().eq(Goods::getStatus, 1);
        queryWrapper.lambda().orderByDesc(Goods::getCreateTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public String findUserIdByGoodsId(String goodsId) {
        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Goods::getUserId).eq(Goods::getId, goodsId);
        return getOne(lambdaQueryWrapper).getUserId();
    }

    /**
     * 用户搜索商品
     *
     * @param title   搜索关键词
     * @param sort    排序方式：0-按创建时间降序，1-按价格升序，2-按价格降序，3-按更新时间降序
     * @param current 当前页码
     * @param size    每页显示数量
     * @return 分页后的商品信息
     */
    @Override
    public Page<Goods> userSearch(String title, String sort, Integer current, Integer size) {
        // 创建查询条件
        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<Goods>();
        lambdaQueryWrapper.like(Goods::getTitle, title)
                .eq(Goods::getStatus, 1);
        // 根据排序方式设置排序条件
        if (sort.equals("0"))
            lambdaQueryWrapper.orderByDesc(Goods::getCreateTime);
        else if (sort.equals("1"))
            lambdaQueryWrapper.orderByAsc(Goods::getPrice);
        else if (sort.equals("2"))
            lambdaQueryWrapper.orderByDesc(Goods::getPrice);
        else if (sort.equals("3"))
            lambdaQueryWrapper.orderByDesc(Goods::getUpdateTime);
        // 执行分页查询并返回结果
        return page(new Page<>(current, size), lambdaQueryWrapper);
    }

    @Override
    public boolean updateGoodsStatusByUserId(String userId, Integer status) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<Goods>();
        updateWrapper.eq(Goods::getUserId, userId).set(Goods::getStatus, status);
        return update(updateWrapper);
    }
}
